package com.ruoyi.project.mobile.service;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.RFactory;
import com.ruoyi.common.utils.mobile.weixin.template.AddCarServerMsg;
import com.ruoyi.common.utils.mobile.weixin.template.MemberHelpMsg;
import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.project.system.car.car.service.ICarService;
import com.ruoyi.project.system.car.img.domain.CarImg;
import com.ruoyi.project.system.car.img.service.ICarImgService;
import com.ruoyi.project.system.dealer.domain.Dealer;
import com.ruoyi.project.system.dealer.service.IDealerService;
import com.ruoyi.project.system.help.domain.MemberHelp;
import com.ruoyi.project.system.help.service.IMemberHelpService;
import com.ruoyi.project.system.membercar.dto.MemberCarDto;
import com.ruoyi.project.system.membercar.service.IMemberCarService;
import com.ruoyi.project.system.service.domain.CarService;
import com.ruoyi.project.system.service.dto.CarServiceDto;
import com.ruoyi.project.system.service.enums.CarServerType;
import com.ruoyi.project.system.service.service.ICarServiceService;

/**
 * 功能：
 *
 * @author：LCL
 * @create：2020/8/6 10:59
 * @version：2020 Version：1.0
 * @company：小牛科技 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api/service")
public class ApiServiceController {

	@Autowired
	private ICarServiceService carServiceService;

	@Autowired
	private IDealerService dealerService;

	@Autowired
	private IMemberHelpService memberHelpService;

	@Autowired
	private ICarImgService carImgService;

	@Autowired
	private IMemberCarService memberCarService;

	/**
	 * 获取门店
	 * @param uid
	 * @param lng
	 * @param lat
	 * @return
	 */
	@GetMapping
	public R serviceReady(@RequestParam String uid,
						   @RequestParam(required = false) Double lng,@RequestParam(required = false) Double lat){
		HashMap<String, Object> map = new HashMap<>();
		//查询客户是否绑车
		MemberCarDto byUid = this.memberCarService.findByUid(uid);
		map.put("hasCar",byUid==null?0:1);
		if (lat!=null){
			map.put("dealer",this.dealerService.findMinDistance(lng,lat));
			return RFactory.generateR(map);
		}
		List<Dealer> dealers = this.dealerService.selectDealerList(new Dealer());
		if(dealers.size()!=0){
			map.put("dealer",dealers.get(0));
			return RFactory.generateR(map);
		}
		return R.error("暂无门店,请联系客服");
	}


	/**
	 * 新增服务预约
	 * @param carService
	 * @return
	 */
	@PostMapping
	public R savaService(@RequestBody CarService carService){
		//判断当前时间是否已经预约满
		CarService select = new CarService();
		select.setDealerId(carService.getDealerId());
		select.setApplyTime(carService.getApplyTime());
		List<CarService> carServices = this.carServiceService.selectNum(select);
		//查询门店信息
		Dealer dealer = this.dealerService.selectDealerById(carService.getDealerId());
		if(carServices.size()>=dealer.getMaxNum()){
			return R.error("该时间段预约已满,请更换时间");
		}
		carService.setStatus(0);
		this.carServiceService.insertCarService(carService);

		//消息接收人的数组
		List<String> receiveList = new ArrayList<String>();

		Map<String,Map<String,List<String>>> dealerList = AppBeanInjector.receive.getDealer();
		Map<String,List<String>> all = dealerList.get("all");
		//无论门店 无论服务 全部推送
		List<String> dealerAll = all.get("all");
		if(dealerAll!=null){
			receiveList.addAll(dealerAll);
		}


		Map<String, List<String>> byDId = dealerList.get(dealer.getId());
		//相关门店 无论服务 全部推送
		List<String> byDidAll = byDId.get("all");
		if(byDidAll!=null){
			receiveList.addAll(byDidAll);
		}
		//相关门店 相关服务 全部推送
		List<String> byDidByType = byDId.get(carService.getType().toString());
		if(byDidByType!=null){
			receiveList.addAll(byDidByType);
		}
		//通知相关人员
		for(int i=0;i<receiveList.size();i++){
			AddCarServerMsg addCarServerMsg = new AddCarServerMsg();
			addCarServerMsg.setToOpenId(receiveList.get(i));
			HashMap<String, String> data = new HashMap<>();
			data.put("name",carService.getName());
			data.put("created",carService.getApplyTime());
			data.put("mobile",carService.getMobile());
			data.put("typeName",CarServerType.getByValue(carService.getType()).getName());
			addCarServerMsg.setContentMsg(data);
			AppBeanInjector.weixinTemplateMsgService.pushMsg(addCarServerMsg);
		}


		return R.ok();
	}

	/**
	 * 查询可预约的时间
	 * @param id
	 * @param date
	 * @return
	 */
	@GetMapping("/date")
	public R AvailableTime(@RequestParam String id, @RequestParam Date date){
		//查询门店的预约时间
		Dealer dealer = this.dealerService.selectDealerById(id);
		Date start = dealer.getStartAppointmentTime();
		Date end = dealer.getEndAppointmentTime();
		//获取日期
		String day = DateUtils.parseDateToStr("yyyy-MM-dd", date);
		// 获取开始时间
		String startH = DateUtils.parseDateToStr("HH", start);
		Integer sh = Integer.parseInt(startH);
		// 获取结束时间
		String endH = DateUtils.parseDateToStr("HH", end);
		Integer eh = Integer.parseInt(endH);

		List dateLis = new ArrayList<HashMap<String,Object>>();
		for (int i = sh; i <=eh ; i++) {
			CarService carService = new CarService();
			carService.setDealerId(id);
			String time = (i < 10 ? "0" + i : i) + ":00-" + ((i + 1) < 10 ? "0" + (i + 1) : (i + 1)) + ":00";
			carService.setApplyTime(day+" "+time);
			List<CarService> carServiceDtos = this.carServiceService.selectNum(carService);
			if(carServiceDtos.size()<dealer.getMaxNum()){
				HashMap<String, Object> map = new HashMap<>();
				map.put("date",time);

				dateLis.add(map);
			}
		}
		return RFactory.generateR(dateLis);

	}

	/**
	 * 一键呼救
	 * @param memberHelp
	 * @return
	 */
	@PostMapping("/help")
	@Transactional
	public R memberHelp(@RequestBody MemberHelp memberHelp){
		memberHelp.setCreated(DateUtils.getNowDate());
		memberHelp.setStatus(0);
		this.memberHelpService.insertMemberHelp(memberHelp);

		//添加图片信息
		for (int i = 0; i < memberHelp.getCarImgs().size(); i++) {
			CarImg carImg = memberHelp.getCarImgs().get(i);
			carImg.setSort(i);
			carImg.setCarId(memberHelp.getId());
			this.carImgService.insertCarImg(carImg);
		}
		List<String> jieshou = AppBeanInjector.weixinConfig.getHelp();
		//通知相关人员
		for(int i=0;i<jieshou.size();i++){
			MemberHelpMsg memberHelpMsg = new MemberHelpMsg();
			memberHelpMsg.setToOpenId(jieshou.get(i));
			HashMap<String, String> data = new HashMap<>();
			data.put("address",memberHelp.getAddress());
			data.put("created",DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",memberHelp.getCreated()));
			data.put("mobile",memberHelp.getMobile());
			memberHelpMsg.setContentMsg(data);
			AppBeanInjector.weixinTemplateMsgService.pushMsg(memberHelpMsg);
		}

		return R.ok();
	}

}
